package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.POLines;
import Models.PurchaseOrder;

public class PurchaseOrderPresenter extends AbstractPresenter<PurchaseOrder> {
	final String SINGLEITEM = "purchaseOrder";
	final String MULTIITEM = "purchaseOrders";
	
	public ArrayList<PurchaseOrder> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public PurchaseOrder tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public PurchaseOrder createItemFromJSONObject(JSONObject jsonObject){
		PurchaseOrder item = new PurchaseOrder();
		try{
			item.setExported(jsonObject.getBoolean("exported"));
			item.setPoDate(timeFormat.parse(jsonObject.getString("PODate")));
			item.setPoID(jsonObject.getInt("poid"));
			item.setPoState(jsonObject.getInt("POState"));
			
			//Set Documents Collection
			ArrayList<POLines> pos = new ArrayList<POLines>();
			if(!jsonObject.isNull("POLinesCollection")){
				Object itm = jsonObject.get("POLinesCollection");
				POLinesPresenter presenter = new POLinesPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						pos.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					pos.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setPos(pos);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(PurchaseOrder item){
		try{
			JSONObject json = new JSONObject();
			json.put("exported", item.isExported());
			json.put("PODate", getDate(item.getPoDate()));
			json.put("poid", item.getPoID());
			json.put("POState", item.getPoState());
			
			//Create Doc Collection
			if(item.getPos()!=null){
				POLinesPresenter presenter = new POLinesPresenter();
				if(item.getPos().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getPos().size(); i++){
						jsonArray.put(presenter.createJSON(item.getPos().get(i)));
					}
					json.put("POLinesCollection", jsonArray);
				}
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public PurchaseOrder getEmptyEntity(){
		PurchaseOrder entity = new PurchaseOrder();
		return entity;
	}
}
